﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using fanfu.Common;
using fanfu.Model;
using fanfu.Business;
using System.Data.SqlClient;

public partial class SystemMenu : BasePage
{
    //所有菜单信息
    private DataTable __SystemMenu = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string menuName = this.searchMenuName.Value.Trim();
        int parentId = int.Parse(this.searchParent.SelectedItem.Value);
        byte isEnd = byte.Parse(this.searchIsEnd.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM SystemMenu WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (menuName != "")
        {
            sqlString += "AND MenuName like @MenuName ";
            paraList.Add(new SqlParameter("@MenuName", "%" + menuName + "%"));
        }
        if (parentId != -1)
        {
            sqlString += "AND ParentId=@ParentId ";
            paraList.Add(new SqlParameter("@ParentId", parentId));
        }
        if (isEnd != 0)
        {
            sqlString += "AND IsEnd=@IsEnd ";
            paraList.Add(new SqlParameter("@IsEnd", isEnd));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        sqlString += "ORDER BY ParentId ASC, Ord ASC";
        #endregion

        //给数据列表赋值
        __SystemMenu = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __SystemMenu.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__SystemMenu.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchMenuName.Value = "";
        this.searchParent.SelectedIndex = 0;
        this.searchIsEnd.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __SystemMenu = new SystemMenuRule().GetAllSystemMenuInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __SystemMenu.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__SystemMenu.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定所有顶级菜单到下拉列表
    /// </summary>
    private void BindSystemMenulList(DropDownList systemMenuList)
    {
        string selectString = "SELECT * FROM SystemMenu WHERE ParentId=0 ORDER BY Ord ASC";
        DataTable systemMenu = SqlHelper.GetDataTable(selectString);
        if (systemMenu.Rows.Count > 0)
        {
            systemMenuList.DataSource = systemMenu;
            systemMenuList.DataTextField = "MenuName";
            systemMenuList.DataValueField = "ID";
            systemMenuList.DataBind();
        }
        systemMenuList.Items.Insert(0, new ListItem("全部菜单", "-1", true));
        systemMenuList.Items.Insert(1, new ListItem("顶级菜单", "0", true));
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.deleteID.Value = "";          //清除删除的ID
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true);  //JS清空控件值
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定系统菜单是否末级到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchIsEnd, typeof(SystemMenuIsEnd));
            //绑定系统菜单状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(SystemMenuFlag));
            //绑定所有顶级菜单到下拉列表
            BindSystemMenulList(this.searchParent);
            BindSystemMenulList(this.drpParent);
            this.drpParent.Items.RemoveAt(0);

            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            SystemMenuModel systemMenu = new SystemMenuRule().GetSystemMenuByID(editID);

            //绑定值到页面控件
            this.txtMenuName.Value = systemMenu.MenuName;
            this.txtMenuUrl.Value = systemMenu.MenuUrl;
            this.txtOrd.Value = systemMenu.Ord.ToString();
            this.drpParent.ClearSelection();
            this.drpParent.Items.FindByValue(systemMenu.ParentId.ToString()).Selected = true;
            this.chkIsEnd.Checked = systemMenu.IsEnd == (byte)SystemMenuIsEnd.yes ? true : false;
            this.chkFlag.Checked = systemMenu.Flag == (byte)SystemMenuFlag.normal ? true : false;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new SystemMenuRule().DeleteSystemMenu(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //刷新系统菜单
        Response.Redirect("SystemMenu.aspx");
        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string menuName = this.txtMenuName.Value.Trim();
        string menuUrl = this.txtMenuUrl.Value.Trim();
        int ord = int.Parse(this.txtOrd.Value);
        int parentId = int.Parse(this.drpParent.SelectedItem.Value);
        string parentName = this.drpParent.SelectedItem.Text;
        byte isEnd = this.chkIsEnd.Checked == true ? (byte)SystemMenuIsEnd.yes : (byte)SystemMenuIsEnd.no;
        byte flag = this.chkFlag.Checked == true ? (byte)SystemMenuFlag.normal : (byte)SystemMenuFlag.delete;
        string editID = this.editID.Value;

        //父级菜单不能是自己
        if (editID == parentId.ToString())
        {
            RunJavascript("PopupMsg('error','错误,父级菜单不能是自己！');", true);
            RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            return;
        }

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            //更新系统菜单
            string sqlString = "UPDATE SystemMenu SET MenuName=@MenuName, MenuUrl=@MenuUrl, Ord=@Ord, ParentId=@ParentId, ParentName=@ParentName, IsEnd=@IsEnd, Flag=@Flag WHERE ID=@ID";
            List<SqlParameter> paraList = new List<SqlParameter>();
            paraList.Add(new SqlParameter("@MenuName", menuName));
            paraList.Add(new SqlParameter("@MenuUrl", menuUrl));
            paraList.Add(new SqlParameter("@Ord", ord));
            paraList.Add(new SqlParameter("@ParentId", parentId));
            paraList.Add(new SqlParameter("@ParentName", parentName));
            paraList.Add(new SqlParameter("@IsEnd", isEnd));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@ID", editID));
            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                //手动级联更新ParentName
                string sqlUpdate = "UPDATE SystemMenu SET ParentName='" + menuName + "' WHERE ParentId=" + editID;
                SqlHelper.ExecuteCommand(sqlUpdate);
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }
        else
        {
            //新增系统菜单
            SystemMenuModel systemMenu = new SystemMenuModel();
            systemMenu.MenuName = menuName;
            systemMenu.MenuUrl = menuUrl;
            systemMenu.Ord = ord;
            systemMenu.ParentId = parentId;
            systemMenu.ParentName = parentName;
            systemMenu.IsEnd = isEnd;
            systemMenu.Flag = flag;
            int result = SqlHelper.ExecuteCommand(SystemMenuModel.GetInsertSQL(), systemMenu.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }

        //刷新系统菜单
        Response.Redirect("SystemMenu.aspx");
        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}